import React, { useState } from 'react'
import { 
  Table, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  Card,
  Row,
  Col,
  Tooltip
} from 'antd'
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  PlayCircleOutlined,
  StopOutlined,
  ApiOutlined,
  DatabaseOutlined,
  CloudOutlined
} from '@ant-design/icons'
import { useQuery } from '@tanstack/react-query'
import { api } from '../services/api'

const { Option } = Select

const Connectors: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [form] = Form.useForm()

  // 获取连接器列表
  const { data: connectors, isLoading, refetch } = useQuery({
    queryKey: ['connectors'],
    queryFn: api.getConnectors,
  })

  const connectorTypes = [
    { value: 'http', label: 'HTTP/REST API', icon: <ApiOutlined /> },
    { value: 'postgresql', label: 'PostgreSQL', icon: <DatabaseOutlined /> },
    { value: 'mysql', label: 'MySQL', icon: <DatabaseOutlined /> },
    { value: 'mongodb', label: 'MongoDB', icon: <DatabaseOutlined /> },
    { value: 's3', label: 'Amazon S3', icon: <CloudOutlined /> },
    { value: 'kafka', label: 'Apache Kafka', icon: <ApiOutlined /> },
  ]

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: any) => (
        <Space>
          {getConnectorIcon(record.connector_type)}
          {text}
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'connector_type',
      key: 'connector_type',
      render: (type: string) => (
        <Tag color={type === 'Source' ? 'blue' : 'green'}>
          {type === 'Source' ? '数据源' : '目标'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          Active: { color: 'green', text: '活跃' },
          Inactive: { color: 'default', text: '未激活' },
          Error: { color: 'red', text: '错误' },
          Testing: { color: 'orange', text: '测试中' },
        }
        const statusInfo = statusMap[status as keyof typeof statusMap] || statusMap.Inactive
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date: string) => new Date(date).toLocaleString('zh-CN'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Tooltip title="测试连接">
            <Button 
              type="text" 
              icon={<PlayCircleOutlined />} 
              onClick={() => handleTestConnector(record.id)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => handleEditConnector(record)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Button 
              type="text" 
              danger 
              icon={<DeleteOutlined />} 
              onClick={() => handleDeleteConnector(record.id)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ]

  const getConnectorIcon = (type: string) => {
    const iconMap = {
      'http': <ApiOutlined style={{ color: '#1890ff' }} />,
      'postgresql': <DatabaseOutlined style={{ color: '#336791' }} />,
      'mysql': <DatabaseOutlined style={{ color: '#4479a1' }} />,
      'mongodb': <DatabaseOutlined style={{ color: '#47a248' }} />,
      's3': <CloudOutlined style={{ color: '#ff9900' }} />,
      'kafka': <ApiOutlined style={{ color: '#231f20' }} />,
    }
    return iconMap[type as keyof typeof iconMap] || <ApiOutlined />
  }

  const handleCreateConnector = () => {
    setIsModalVisible(true)
    form.resetFields()
  }

  const handleEditConnector = (connector: any) => {
    setIsModalVisible(true)
    form.setFieldsValue(connector)
  }

  const handleDeleteConnector = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个连接器吗？此操作不可撤销。',
      onOk: async () => {
        try {
          await api.deleteConnector(id)
          refetch()
        } catch (error) {
          console.error('删除连接器失败:', error)
        }
      },
    })
  }

  const handleTestConnector = async (id: string) => {
    try {
      await api.testConnector(id)
      Modal.success({
        title: '测试成功',
        content: '连接器测试通过！',
      })
    } catch (error) {
      Modal.error({
        title: '测试失败',
        content: '连接器测试失败，请检查配置。',
      })
    }
  }

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields()
      await api.createConnector(values)
      setIsModalVisible(false)
      refetch()
    } catch (error) {
      console.error('创建连接器失败:', error)
    }
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <h1>连接器管理</h1>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleCreateConnector}
        >
          创建连接器
        </Button>
      </div>

      {/* 连接器类型卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        {connectorTypes.map((type) => (
          <Col span={4} key={type.value}>
            <Card 
              hoverable
              size="small"
              style={{ textAlign: 'center' }}
              onClick={() => {
                setIsModalVisible(true)
                form.setFieldsValue({ connector_type: type.value })
              }}
            >
              <div style={{ fontSize: 24, marginBottom: 8 }}>
                {type.icon}
              </div>
              <div>{type.label}</div>
            </Card>
          </Col>
        ))}
      </Row>

      <Table 
        columns={columns} 
        dataSource={connectors} 
        loading={isLoading}
        rowKey="id"
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 个连接器`,
        }}
      />

      <Modal
        title="创建连接器"
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="连接器名称"
            rules={[{ required: true, message: '请输入连接器名称' }]}
          >
            <Input placeholder="输入连接器名称" />
          </Form.Item>

          <Form.Item
            name="connector_type"
            label="连接器类型"
            rules={[{ required: true, message: '请选择连接器类型' }]}
          >
            <Select placeholder="选择连接器类型">
              {connectorTypes.map((type) => (
                <Option key={type.value} value={type.value}>
                  <Space>
                    {type.icon}
                    {type.label}
                  </Space>
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea rows={3} placeholder="输入连接器描述" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Connectors
